package cn.softgame.jserver.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpHeadHelper {
	public final static String encoding="UTF-8";
	public final static String nameContentType="Content-Type";
	public final static String reqStringContentType="application/x-www-form-urlencoded";
	public final static String reqObjectContentType="application/octet-stream";
	public final static String resStringContentType="text/html";
	public final static String resObjectContentType="application/octet-stream";
	
	public final static String head11="HEAD_11";
	public final static String head12="HEAD_12";
	public final static String head13="HEAD_13";
	public final static String split=" Split_index";
	
	public static byte[] assembleRequest(byte[] bytes){
		byte[] result=null;
		try{
			String header = getPostHeader("",0);
			byte[] headers = header.getBytes("UTF-8");
			int length = bytes.length + headers.length;
			result = new byte[length];
			System.arraycopy(headers, 0, result, 0, header.length());
			System.arraycopy(bytes, 0, result, headers.length, bytes.length);
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getGetHeader(){
		StringBuffer sb = new StringBuffer("GET ");
		sb.append("/HttpHeader");
		sb.append(" HTTP/1.0\r\n");
		sb.append(getBaseHeads());
		sb.append("\r\n");
		return sb.toString();
	}

	public static String getPostHeader(String contentType, int contentLength) {
		StringBuffer sb = new StringBuffer("POST").append(" ");
		sb.append("/HttpHeader").append(" ").append("HTTP/1.0").append("\r\n");
		sb.append(getBaseHeads());
		if("".equals(contentType)){
			contentType=reqStringContentType;
		}
		sb.append("Content-type:").append(contentType).append("\r\n");
		if(contentLength!=0){
			sb.append("Content-length:").append(contentLength).append("\r\n");
		}
		sb.append("\r\n");
		return sb.toString();
	}
	
	private static String getBaseHeads() {
		StringBuffer sb = new StringBuffer("User-Agent:ChatClient\r\n");
		sb.append("Accept:www/source; text/html; image/gif; */*\r\n");
		return sb.toString();
	}

	public static byte[] assembleResponse(byte[] bytes){
		byte[] result=null;
		try{
			String header = getResponseHeader("",0);
			byte[] headers = header.getBytes("UTF-8");
			int length=bytes.length+headers.length;
			result=new byte[length];
			System.arraycopy(headers, 0, result, 0, header.length());
			System.arraycopy(bytes, 0, result, headers.length, bytes.length);
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("deprecation")
	public static String getResponseHeader(String contentType, int statusCode) {
		if(statusCode==0){
			statusCode=200;
		}
		if("".equals(contentType)){
			contentType=resStringContentType;
		}
		StringBuffer sb = new StringBuffer("HTTP/1.1").append(" ");
		sb.append(statusCode).append(" ").append("OK").append("\r\n");
		Date d = new Date(System.currentTimeMillis());
		sb.append("Date:").append(d.toGMTString()).append("\r\n");
		sb.append("Server:").append(" TCP/UDP Server").append("\r\n");
		sb.append("Connection:").append("close").append("\r\n"); ;
		sb.append(nameContentType).append(":").append(contentType).append(
	        "\r\n");
		sb.append("\r\n");
		return sb.toString();
	}
	
	/**
	 * 分析Http信息，分离头部和内容两部分
	 * 头部信息保存在Map中
	 * @param bytes
	 * @return
	 */
	public static Map parse(byte[] bytes){
		Map map = new HashMap();
		try{
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			//分解头部放入header中
			byte[] header = new byte[bytes.length];
			int count=0;
			int index=0;
			int word=-1;
			boolean begin=false;
			// 解析第一行
			while((word=bis.read())!=-1){
				index++;
				if(word=='\r'){
					word=bis.read();
					header[count++]=(byte) word;
					index++;
					if(word=='\n'){
						word=bis.read();
						index++;
						if(word=='\r'){
							index++;
							word=bis.read();
							if(word=='\n'){
								break;
							}
						}
					}
				}
				header[count++]=(byte) word;
			}
			
			//记录下从byte数组第几个开始是正文部分
			map.put(split, new Integer(index));
			
			//以下是提取头部的信息
			InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(header));
			BufferedReader br = new BufferedReader(isr);
			
			//第一行头部信息
			String w=br.readLine();
			String[] strings = w.split(" ");
			map.put(head11, strings[0]);
			map.put(head12, strings[1]);
			map.put(head13, strings[2]);
			
			//一直查询到Http的空行
			while((w=br.readLine())!=null){
				if(w.indexOf(":")!=-1){
					String[] strings2=w.split(":");
					map.put(strings[0], strings[1]);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 获取Http信号中的内容部分
	 * @param bytes
	 * @return
	 */
	public static byte[] getContent(byte[] bytes){
		byte[] result=null;
		try{
			Map map = parse(bytes);
			int index=((Integer)map.get(split)).intValue();
			
			int length=bytes.length-index;
			result=new byte[length];
			System.arraycopy(bytes, index, result, 0, length);
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
		
	}
	
	public static byte[] getContent(byte[] bytes,Map map){
		byte[] result=null;
		try{
			int index=((Integer)map.get(split)).intValue();
			int length=bytes.length-index;
			result=new byte[length];
			System.arraycopy(bytes, index, result, 0, length);
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	private static String getNoSpaces(String sr){
		String newString = null;
		if(sr.indexOf(" ")==0){
			sr=sr.substring(1);
		}
		int maxIndex=sr.length()-1;
		if(sr.lastIndexOf(" ")==maxIndex){
			newString=sr.substring(0, maxIndex);
		}
		return newString;
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
	    String HttpPOSTHeader = "HTTP/1.1 200 OK\r\n";
	    String HttpPOSTHeader2 = "Date: Tue, 14 Sep 1999 02:19:57 GMT\r\n";
	    String HttpPOSTHeader3 = "\r\n";
	    String HttpPOSTHeader4 = "Server: Apache/1.2.6";
		
		String content = "我是许权";
//		byte[] result2 = HttpHeadHelper.assembleResponse(content.getBytes("UTF-8"));
      byte[] result2 = HttpHeadHelper.assembleRequest(content.getBytes("UTF-8"));

		byte[] reqContent = HttpHeadHelper.getContent(result2);
		System.out.print("reqContent==" + new String(reqContent) + "==");
	}
}
